package com.jinbm.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理, 拦截指定包下的所有异常
 *
 * @author Jinbm
 * @date 2024/7/8
 * @since 1.0
 */
@ControllerAdvice("com.jinbm.controller") // 指定拦截的包
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 拦截SaTokenException权限异常
     *
     * @author Jinbm
     * @date 2024/7/9
     * @param e
     * @return Result.error
     */
    @ExceptionHandler(SaTokenException.class)
    @ResponseBody
    public Result saTokenExceptionHandler(HttpServletRequest request,SaTokenException e) {
        log.error("权限异常", e);
        return Result.error(ResultEnum.FORBIDDEN.code,ResultEnum.FORBIDDEN.msg + e.getMessage());
    }

    /**
     * 业务异常拦截
     *
     * @author Jinbm
     * @date 2024/7/9
     * @param request
     * @param e
     * @return Result.error
     */
    @ExceptionHandler
    @ResponseBody
    public Result customExceptionHandler(HttpServletRequest request,CustomException e) {
        log.error("业务异常", e);
        return Result.error(ResultEnum.BUSINESS_ERROR.code, e.getMessage());
    }

    /**
     * 主要用于Exception异常
     *
     * @author Jinbm
     * @date 2024/7/8
     * @param e
     * @return Result.error
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody // 返回json数据
    public Result exceptionHandler(HttpServletRequest request, Exception e) {
        log.error("系统异常:", e);
        return Result.error(ResultEnum.SERVER_ERROR.code,"系统异常",e.getMessage());
    }
}
